package com.julinggame.nettyim.handler;

import com.alibaba.fastjson2.JSON;
import com.julinggame.nettyim.CommentCode;
import com.julinggame.nettyim.CommentType;
import com.julinggame.nettyim.ImServer;
import com.julinggame.nettyim.Result;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
       try {
           CommentCode commentCode = JSON.parseObject(msg.text(), CommentCode.class);
           switch (CommentType.match(commentCode.getCode())) {
               case CONNECT ->
                       ConnectHandler.execute(ctx,commentCode);
               case CHAT -> ChatHandler.execute(ctx,msg);
               default -> ctx.channel().writeAndFlush(Result.fail("不支持的指令"));
           }
       } catch (Exception e) {
           ctx.channel().writeAndFlush(Result.fail(e.getMessage()));
       }

    }
}
